package org.example;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Random;

@Aspect  // 表示这是一个切面类
@Component  // 让 Spring 管理
public class OrderServiceAspect {

    // 定义切点：匹配 OrderServiceImpl 的三个方法
    @Pointcut("execution(* com.example.homework6.service.OrderServiceImpl.add(..)) || " +
            "execution(* com.example.homework6.service.OrderServiceImpl.delete(..)) || " +
            "execution(* com.example.homework6.service.OrderServiceImpl.find(..))")
    public void serviceMethods() {}

    // 1. 前置增强：add, delete, find 前执行
    @Before("serviceMethods()")
    public void beforeAdvice() {
        System.out.println("👋 hello, 我是一个前置增强");
    }

    // 2. 后置增强：add, delete 后执行（不管是否异常）
    @After("execution(* com.example.homework6.service.OrderServiceImpl.add(..)) || " +
            "execution(* com.example.homework6.service.OrderServiceImpl.delete(..))")
    public void afterAdvice() {
        System.out.println("👋 bye, 我是一个后置增强");
    }

    // 3. 返回值增强：获取 find() 的返回值
    @AfterReturning(pointcut = "execution(int com.example.homework6.service.OrderServiceImpl.find(..))", returning = "result")
    public void afterReturning(int result) {
        System.out.println("✅ 方法执行成功，返回值为: " + result);
    }

    // 4. 环绕增强：统计方法执行时间
    @Around("serviceMethods()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        long start = System.currentTimeMillis();

        System.out.println("⏱️  开始执行方法: " + methodName);

        Object result = null;
        try {
            result = joinPoint.proceed(); // 执行原方法
        } catch (Throwable e) {
            throw e;
        } finally {
            long end = System.currentTimeMillis();
            System.out.println("⏱️  方法 " + methodName + " 执行耗时: " + (end - start) + " 毫秒");
        }
        return result;
    }

    // 5. 权限校验：add, delete 前检查权限，无权限则中断
    @Before("execution(* com.example.homework6.service.OrderServiceImpl.add(..)) || " +
            "execution(* com.example.homework6.service.OrderServiceImpl.delete(..))")
    public void checkPermission() {
        Random random = new Random();
        int permission = random.nextInt(2); // 0 或 1

        if (permission == 0) {
            System.out.println("✅ 权限校验通过，允许执行操作");
        } else {
            System.out.println("❌ 权限校验失败，禁止执行操作！");
            throw new SecurityException("权限不足，操作被拒绝");
        }
    }
}